//
//  UIButton+clickCount.m
//  jkds
//
//  Created by perfay on 2018/3/30.
//  Copyright © 2018年 perfaylk. All rights reserved.
//

#import "UIButton+clickCount.h"

typedef void(^testBlock)();

@interface UIButton ()

@property(nonatomic,copy) testBlock currentActionBlock;
@end

@implementation UIButton (clickCount)

static char xw_currentActionBlock;

- (testBlock)currentActionBlock{
    return objc_getAssociatedObject(self, &xw_currentActionBlock);
}
- (void)setCurrentActionBlock:(testBlock)currentActionBlock{
    objc_setAssociatedObject(self, &xw_currentActionBlock, currentActionBlock, OBJC_ASSOCIATION_COPY);
}
/*
- (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents{
    //block循环引用
    __weak typeof(target) weakTarget = target;
    //利用 关联对象 给UIButton 增加了一个 block
    [self  setCurrentActionBlock:^{
        //运行时 发送 消息 执行方法
        ((void (*)(void *, SEL, UIView *))objc_msgSend)((__bridge void *)(weakTarget), action , nil);
    }];
    //拦截了本身要执行的action 先执行，写下来的 xw_clicked:方法
    [super addTarget:self action:@selector(xw_clicked:) forControlEvents:controlEvents];
}
*/

//拦截了按钮点击后要执行的代码
- (void)xw_clicked:(UIButton *)sender{
    //统计
    self.btnClickedCount++;
    NSLog(@"%@ 点击 %ld次 ",[sender titleForState:UIControlStateNormal], self.btnClickedCount);
    sender.currentActionBlock();
}
static char xw_btnClickedCount;
- (NSInteger)btnClickedCount{
    id tmp = objc_getAssociatedObject(self, &xw_btnClickedCount);
    NSNumber *number = tmp;
    return number.integerValue;
}

- (void)setBtnClickedCount:(NSInteger)btnClickedCount{
    objc_setAssociatedObject(self, &xw_btnClickedCount, @(btnClickedCount), OBJC_ASSOCIATION_ASSIGN);
}
static char xw_btnClickedPoint;

- (NSString *)clickPoint{
    return objc_getAssociatedObject(self, &xw_btnClickedPoint);
}
-(void)setClickPoint:(NSString *)clickPoint{
    objc_setAssociatedObject(self, &xw_btnClickedPoint, clickPoint, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    UIView *responsView = [super hitTest:point withEvent:event];
    if (responsView == self) {
        self.clickPoint = NSStringFromCGPoint(point);
        NSString *pstring = [NSString stringWithFormat:@"%@ 点击 :(%f,%f)) ",[self titleForState:UIControlStateNormal], point.x,point.y];
        NSLog(@"%@",pstring);
//        [MobClick event:@"1000" label:pstring];
    }
    return responsView;
}

@end
